<script setup>
import  { tool }  from "../tool/index"
import { ref, watch, onMounted, reactive, inject } from "vue"
import { Plus } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import { useRouter } from "vue-router"
// API 地址
const getImgPath = tool.serverPath + "api/app_api/image/download?fileName="
// 初始化数据
const props = defineProps(['BlogId'])
const router = useRouter()
const store = inject('store')
const user = store.state.user
// 用户选择的分类
var category = ref([])
// 博客对象
var newBlog = reactive({
  title: "",
  content: "",
  image: undefined,
  author_id: user.id,
  created_at: undefined,
  updated_at: undefined,
  category: undefined,
  label_1: null,
  label_2: null,
  label_3: null,
  label_4: null,
  label_5: null,
})
// 为文件对象转 URL 做准备
const imageUrl = ref()
// 为图片做对比
const imageTemp = ref()
// 获取文件选择对象，进行Ref绑定
const fileInputRef = ref(null)
// 为文件存储做准备
const selectedImage = ref(null)
// 标签操作
var tag = ref([])
// 标签交换
const tagTemp = ref(undefined)
// 分类选择
const cascaderOptions = ref([])

// 刷新页面防止数据混合
watch(() => props.BlogId, () => {
  location.reload()
})
// 监听用户选择的分类
watch(() => category.value, (newValue) => {
  newBlog.category = newValue[0]
})

// 触发文件选择事件
function openFileInput() {
  fileInputRef.value.click()
}
// 封面对象转存
function handleFileChange(event) {
  // 获取文件对象进行存储
  const file = event.target.files[0]
  const type = tool.fileApi.imageType(file)
  if(type.type == "err"){
    ElMessage({
      type:"warning",
      message:"文件格式有误，请检查大小:(< 5 MB) 及文件类型:(图片)"
    })
  }
  // 将文件对象转存
  selectedImage.value = file
  // 判断用户是否替换了图片
  imageTemp.value = file.name
  // 将文件对象转换为URL
  imageUrl.value = URL.createObjectURL(file)
}
// 添加标签
function addTag() {
  for (let index = 0; index < tag.value.length; index++) {
    if (tagTemp.value == tag.value[index]) {
      ElMessage('标签不允许重复')
      return
    }
  }
  if (tag.value.length < 5) {
    if (tagTemp.value != "") {
      tag.value.push(tagTemp.value)
      tagTemp.value = null
    } else {
      ElMessage('标签不允许为空')
    }
  } else {
    ElMessage('标签数量已满')
  }
}
// 标签删除
function deleteTag(index) {
  tag.value.splice(index, 1)
}
// 查询分类
async function blogOptions() {
  try {
    const data = {
        key: "Search",
        data: {
          key: ["ID"],
          value: [""]
        }
      }
        const options = await tool.axiosApi("category", data, "get")
    for (let index = 0; index < options.data.length; index++) {
      cascaderOptions.value.push({
        value: options.data[index].id,
        label: options.data[index].name,
      })
    }
  } catch (error) {

  }
}
// 查询文章
async function SearchBlog(value) {
  try {
    const data = {
        key: "Search",
        data: {
          key: ["id"],
          value: [value]
        }
      }
    const blog = await tool.axiosApi("article", data, "get")
    newBlog.title = blog.data[0].title
    newBlog.content = blog.data[0].content
    imageTemp.value = newBlog.image = blog.data[0].image
    if (blog.data[0].image != null && blog.data[0].image != undefined) {
      imageUrl.value = getImgPath + blog.data[0].image
    }
    category.value[0] = newBlog.category = Number(blog.data[0].category)
    newBlog.updated_at = new Date()
    for (let index = 0; index < 5; index++) {
      if (blog.data[0][`label_${index + 1}`] != null) {
        tag.value.push(blog.data[0][`label_${index + 1}`])
      }
    }
  } catch (error) {

  }
}
// 初始化数据
onMounted(() => {
  blogOptions()
  if (props.BlogId != `false`)
    SearchBlog(props.BlogId)
})
// 图片上传到服务器
async function uploadImage() {
  try {
    const file = selectedImage.value
    console.log(file)
    const response = await tool.fileApi.update(file,newBlog.image)
    console.log(response)
    return response.fileName
  } catch (error) {
  }
}
// 确认发表
async function uploadBlog() {
  try {
    if (newBlog.title == "") {
      ElMessage({
        message: '标题不得为空',
        type: 'warning',
      })
      return
    }
    if (newBlog.content == "") {
      ElMessage({
        message: '内容不得为空',
        type: 'warning',
      })
      return
    }
    if (newBlog.category == undefined) {
      ElMessage({
        message: '分类不得为空',
        type: 'warning',
      })
      return
    }
    // 添加标签进入 NewBlog
    for (let index = 0; index < 5; index++) {
      newBlog[`label_${index + 1}`] = tag.value[index] == undefined ? "null" : tag.value[index]
    }
    // 将图片上传
    if (imageTemp.value != newBlog.image){
      newBlog.image = await uploadImage()
    }
    if (props.BlogId == `false`) {
      newBlog.updated_at = newBlog.created_at = new Date()
      const data = {
        key: "add",
        data: {
          key: Object.keys(newBlog),
          value: Object.values(newBlog)
        }
      }
      console.log(data)
        const addBlog = await tool.axiosApi("article", data, "post")     
      if (addBlog.message) {
        ElMessage({
          message: '发布成功，正在跳转......',
          type: 'success',
        })
        await router.push("/")
      } else {
        ElMessage({
          message: '发布失败，请检查后重试',
          type: 'error',
        })
      }
    } else {
      newBlog.updated_at = new Date()
      const data = {
        key: "update",
        data: {
          key: Object.keys(newBlog),
          value: Object.values(newBlog)
        },
        where: {
          key: ["id"],
          value: [props.BlogId]
        }
      }
        const updateBlog = await tool.axiosApi("article", data, "post")
      if (updateBlog.message) {
        ElMessage({
          message: '更新成功，正在跳转......',
          type: 'success',
        })
        await router.push("/")
      } else {
        ElMessage({
          message: '更新失败，请检查后重试',
          type: 'error',
        })
      }
    }
  } catch (error) {

  }
}
</script>

<template>
  <div class="CompileContent">
    <div class="title">
      <input v-model="newBlog.title" type="text" placeholder="请输入标题 (5~20个字)" minlength="5" maxlength="50" />
      <span>{{ newBlog.title.length }}/50</span>
    </div>
    <el-divider border-style="dashed" />
    <div class="content">
      <el-input class="textarea" v-model="newBlog.content" :autosize="{ minRows: 15, maxRows: 999 }" resize="none"
        size="medium " type="textarea" minlength="5" maxlength="10000" placeholder="# 请输入内容（10-1400个字）" />
      <div class="ContentBottom">
        <el-button class="tag" v-for="(item, index) in tag" :key="item" :type="primary" @click="deleteTag(index)" link>
          # {{ item }}
        </el-button>
        <el-button v-show="tag.length == 0" type="danger"> 暂无标签 </el-button>
        <span>{{ newBlog.content.length }}/10000</span>
      </div>
    </div>
    <el-divider border-style="dashed" />
    <el-row :gutter="10">
      <el-col class="image-uploader" :span="8">
        <input ref="fileInputRef" type="file" @change="handleFileChange($event)">
        <el-image v-if="imageUrl" :src="imageUrl" @click="openFileInput()"> </el-image>
        <div v-else @click="openFileInput()">
          <el-icon :size="30">
            <Plus />
          </el-icon>
        </div>
      </el-col>
      <el-col :span="8">
        <div class="addTag">
          <input type="text" v-model="tagTemp" maxlength="10" placeholder="只能有五个标签">
          <el-button type="primary" @click="addTag()">添加标签</el-button>
        </div>
        <div class="Category">
          <el-cascader placeholder="请选择分类" style="width: 100%;" v-model="category" class="cascader"
            :options="cascaderOptions" clearable />
        </div>
      </el-col>
      <el-col class="addBlog" :span="8">
        <el-button v-if="props.BlogId != `false`" type="primary" @click="uploadBlog()">更新博客</el-button>
        <el-button v-else type="primary" @click="uploadBlog()">确认发表</el-button>

      </el-col>
    </el-row>
  </div>
</template>

<style scoped>
.CompileContent {
  overflow: hidden;
  background-color: white;
  border-radius: 5px;
  margin: auto;
  padding: 30px;
  margin-top: 10px;
  margin-bottom: 10px;
  width: 800px;
}

.CompileContent input[type="text"] {
  border: none;
  outline: none;
  padding: 0;
  margin: 0;
  font-family: inherit;
  font-size: inherit;
  color: inherit;
}

.CompileContent .title {
  padding: 5px;
  position: relative;
}

.CompileContent .title input[type="text"] {
  color: rgb(46, 46, 46);
  font-size: 30px;
  height: 50px;
  width: 90%;
}

.CompileContent span {
  color: rgb(194, 194, 194);
  position: absolute;
  right: 5px;
  bottom: 5px;
}

.CompileContent .content {
  position: relative;
}

.CompileContent .content .el-textarea {
  font-size: 15px;
  margin-bottom: 20px;
}

.title input[type="text"]::placeholder {
  font-weight: bold;
  color: rgb(171, 171, 171);
}

.el-divider {
  margin-top: 5px;
}

.image-uploader .el-icon,
.el-image {
  border-radius: 10px;
  background-color: rgb(233, 233, 233);
  width: 200px;
  height: 120px;
}

.image-uploader input[type="file"] {
  display: none;
}

.CompileContent .ContentBottom {
  position: relative;
}

.ContentBottom .tag {
  color: rgb(171, 171, 171);
}

.ContentBottom .tag:hover {
  color: rgb(254, 67, 67);
}

.CompileContent .addTag input[type="text"] {
  width: 150px;
  margin-right: 10px;
  padding-left: 5px;
  padding-right: 5px;
  padding-bottom: 5px;
  border-bottom: 1px solid rgb(171, 171, 171);
}

.CompileContent .addTag input[type="text"]::placeholder {
  font-size: 15px;
  color: rgb(171, 171, 171);
}

.CompileContent .Category {
  margin-top: 10px;
}

.CompileContent .Category .cascader {
  margin: 0;
  display: none;
  width: 3321px;
}

.CompileContent .addBlog {
  display: grid;
  place-items: center;
  text-align: center;
}

.CompileContent .addBlog .el-button {
  font-size: 15px;
  border-radius: 10px;
  width: 150px;
  height: 90px;
}
</style>